/* 封装数据库操作工具 */
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/cs2210";
const ObjectId = require('mongodb').ObjectId


class Database {
	connection = null // 数据库连接
	dbo = null // 数据库对象

	constructor() {

	}

	async init() {
		// if(this.dbo){
		//     return
		// }
		try {
			this.connection = await MongoClient.connect(url)
			this.dbo = this.connection.db()
		} catch (err) {
			console.log(err);
		}
	}

	// 新增
	async insert(collectionName, data) {
		await this.init()
		let res
		try {
			res = await this.dbo.collection(collectionName).insertOne(data)
		} catch (err) {
			console.log(err);
		}
		// this.connection.close()
		return res
	}

	// 修改
	async update(collectionName, where, data) {
		await this.init()
		let res
		if (where._id && typeof where._id == 'string') {
			where._id = ObjectId(where._id)
		}
		try {
			res = await this.dbo.collection(collectionName).updateOne(where, { $set: data })
		} catch (err) {
			console.log(err);
		}
		// this.connection.close()
		return res
	}

	// 删除
	async delete(collectionName, where) {
		await this.init()
		let res
		if (where._id && typeof where._id == 'string') {
			where._id = ObjectId(where._id)
		}
		try {
			res = await this.dbo.collection(collectionName).deleteOne(where)
		} catch (err) {
			console.log(err);
		}
		// this.connection.close()
		return res
	}

	// 查询 分页 搜索 排序
	async find(collectionName, { where, sort, skip, limit }) {
		await this.init()
		let res
		try {
			res = await this.dbo.collection(collectionName).find(where).sort(sort).skip(skip * 1).limit(limit * 1)
				.toArray()
		} catch (err) {
			console.log(err);
		}
		// this.connection.close()
		return res
	}

	// 仅获取全部数据
	async findAll(collectionName, where = {}, sort = {}) {
		await this.init()
		let res
		try {
			res = await this.dbo.collection(collectionName).find(where).sort(sort).toArray()
		} catch (err) {
			console.log(err);
		}
		// this.connection.close()
		return res
	}

	// 根据条件查询一条数据
	async findOne(collectionName, where) {
		await this.init()
		let res
		if (where._id && typeof where._id == 'string') {
			where._id = ObjectId(where._id)
		}
		try {
			res = await this.dbo.collection(collectionName).find(where).toArray()
		} catch (err) {
			console.log(err);
		}
		// this.connection.close()
		return res
	}

	//获取总条数
	async total(collectionName, where) {
		await this.init()
		let res
		try {
			res = await this.dbo.collection(collectionName).countDocuments(where)
		} catch (err) {
			console.log(err)
		}
		// this.connection.close()
		return res
	}
}

module.exports = new Database()
